package com.iqiyi.pps.epg.core.rpc.channel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.kiwi.utils.DateHelper;
import com.iqiyi.kiwi.utils.HttpClientConnection;
import com.iqiyi.pps.epg.api.model.web.channel.*;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.server.web.channel.ChannelWebService;
import com.iqiyi.pps.epg.api.server.web.channel.ChannelWebServiceConstants;
import com.iqiyi.pps.epg.core.model.channel.*;
import com.iqiyi.pps.epg.core.model.log.InterfaceLog;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.rpc.program.ProgramWebServiceImpl;
import com.iqiyi.pps.epg.core.rpc.qipu.Composite.AlternatePlayCollectionImpl;
import com.iqiyi.pps.epg.core.service.broadcast.BroadcastControlService;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.log.InterfaceLogService;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import com.iqiyi.pps.epg.core.service.stream.LiveChannelStreamService;
import com.iqiyi.pps.epg.core.utils.*;
import org.apache.commons.lang.StringUtils;
import org.apache.thrift.TException;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: rainliang
 * Mail: rainliang@qiyi.com
 * Date: 2014/7/6
 * Time: 23:23
 * Desc:
 */
public class ChannelWebServiceImpl implements ChannelWebService.Iface {

    public static final String APC_ADD = Configuration.getString("apc.add");
    public static Logger logger = LoggerFactory.getLogger(ChannelWebServiceImpl.class);

    @Override
    public long create(TChannel entity) throws TException {
        long result = 0;
        if (entity != null) {
            ChannelBase channelBase = new ChannelBase();
            channelBase.setName(entity.getName());
            channelBase.setQipuId(entity.getQipuId());
            channelBase.setOperator(entity.getOperator());
            channelBase.setOldQipuId(entity.getOldQipuId());
            channelBase.setShortName(entity.getShortName());
            channelBase.setUniversalCode(entity.getUniversalCode());
            channelBase.setDescription(entity.getDescription());
            channelBase.setPassportId(entity.getPassportId());
            channelBase.setPpsBaikeId(entity.getPpsBaikeId());
            channelBase.setLiveType(entity.getLiveType());
            channelBase.setType(entity.getType());
            channelBase.setLocation(entity.getLocation());
            channelBase.setMaxPlaybackPeriod(entity.getMaxPlaybackPeriod());
            channelBase.setTempName(entity.getTempName());
            if (StringUtils.isNotBlank(entity.getTempStartTime())) {
                channelBase.setTempStartTime(Timestamp.valueOf(entity.getTempStartTime()));
            }
            if (StringUtils.isNotBlank(entity.getTempEndTime())) {
                channelBase.setTempEndTime(Timestamp.valueOf(entity.getTempEndTime()));
            }
            channelBase.setQitanId(entity.getQitanId() > 0 ? entity.getQitanId() : getQiTanId(entity.getName()));
            channelBase.setOrderBy(entity.getOrderBy());
            channelBase.setIsEnable(entity.getIsEnable());
            channelBase.setIsSync(1);
            channelBase.setLogoUrl("");
            channelBase.setLogoEntityId(entity.getLogoEntityId());
            channelBase.setAllowPopups(entity.getAllowPopups());
            channelBase.setShouldDisplay(entity.getShouldDisplay());
            channelBase.setIsQiyiProduced(entity.getIsQiyiProduced());
            channelBase.setExclusiveStatusIqiyi(entity.getExclusiveStatusIqiyi());
            channelBase.setInterruptHintType(entity.getInterruptHintType());
            channelBase.setSliceDelay(entity.getSliceDelay());
            channelBase.setSubjectUrl(entity.getSubjectUrl());
            channelBase.setAutomation(entity.getAutomation());
            channelBase.setUserCount(entity.getUserCount());
            channelBase.setFormal(entity.getFormal());
            channelBase.setCyclical(entity.getCyclical());
            channelBase.setAlternatePlayCollection(entity.getAlternatePlayCollection());
            channelBase.setCarouselTableNo(entity.getCarouselTableNo());
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            long start1 = System.currentTimeMillis();
            service.saveBase(channelBase);
            long start2 = System.currentTimeMillis();
            logger.info("[ChannelWebServiceImpl][create][saveBase][time={}]", (start2 - start1));
            result = channelBase.getId();
            if (result > 0) {
                // 调用接口添加备播库资源
                String apc = channelBase.getAlternatePlayCollection();
                if (null != apc && !"".equals(apc)) {
                    apcAdd(result, apc);
                }

                //投递图片
                JSONArray jsonArray = JSON.parseArray(entity.getLogoUrl());
                productImg(result, jsonArray);
                ChannelBoss channelBoss = new ChannelBoss();
                channelBoss.setFatherId(result);
                channelBoss.setIsMemeberFree(entity.getIsMemeberFree());
                if (StringUtils.isNotBlank(entity.getPaidStartTime())) {
                    channelBoss.setPaidStartTime(Timestamp.valueOf(entity.getPaidStartTime()));
                }
                if (StringUtils.isNotBlank(entity.getPaidEndTime())) {
                    channelBoss.setPaidEndTime(Timestamp.valueOf(entity.getPaidEndTime()));
                }
                channelBoss.setStatus("FREE");
                channelBoss.setIsMemberOnly(0);
                long start3 = System.currentTimeMillis();

                service.saveBoss(channelBoss);
                long start4 = System.currentTimeMillis();
                logger.info("[ChannelWebServiceImpl][create][saveBoss][time={}]", (start4 - start3));
                if( StringUtils.isNotBlank( entity.getTag()) ){
                    String[] tagArr = entity.getTag().split(",");
                    for (int i = 0; i < tagArr.length; i++) {
                        ChannelTag channelTag = new ChannelTag();
                        channelTag.setFatherId(result);
                        channelTag.setTag2(Long.parseLong(tagArr[i].split("_")[1]));
                        channelTag.setTag1(Long.parseLong(tagArr[i].split("_")[0]));
                        service.saveTag(channelTag);
                    }
                }

                long start5 = System.currentTimeMillis();
                logger.info("[ChannelWebServiceImpl][create][saveTag][time={}]", (start5 - start4));
            }
        }
        return result;
    }

    @Override
    public boolean edit(TChannel entity) throws TException {
        boolean ret = false;
        int oldMaxPlaybackPeriod = 0;
        if (entity != null) {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            ChannelBase channelBase = service.getChannelBase(entity.getId());
            oldMaxPlaybackPeriod = channelBase.getMaxPlaybackPeriod();

            channelBase.setName(entity.getName());
            channelBase.setQipuId(entity.getQipuId());
            channelBase.setOldQipuId(entity.getOldQipuId());
            channelBase.setShortName(entity.getShortName());
            channelBase.setUniversalCode(entity.getUniversalCode());
            channelBase.setOperator(entity.getOperator());
            channelBase.setDescription(entity.getDescription());
            channelBase.setPassportId(entity.getPassportId());
            channelBase.setPpsBaikeId(entity.getPpsBaikeId());
            channelBase.setLiveType(entity.getLiveType());
            channelBase.setType(entity.getType());
            channelBase.setLocation(entity.getLocation());
            channelBase.setMaxPlaybackPeriod(entity.getMaxPlaybackPeriod());
            channelBase.setTempName(entity.getTempName());
            if (StringUtils.isNotBlank(entity.getTempStartTime())) {
                channelBase.setTempStartTime(Timestamp.valueOf(entity.getTempStartTime()));
            }
            if (StringUtils.isNotBlank(entity.getTempEndTime())) {
                channelBase.setTempEndTime(Timestamp.valueOf(entity.getTempEndTime()));
            }
            channelBase.setQitanId(entity.getQitanId() > 0 ? entity.getQitanId() : getQiTanId(entity.getName()));
            channelBase.setLogoUrl("");
            channelBase.setLogoEntityId(entity.getLogoEntityId());
            channelBase.setOrderBy(entity.getOrderBy());
            channelBase.setIsEnable(entity.getIsEnable());
            channelBase.setIsSync(1);
            channelBase.setAddTime(Timestamp.valueOf(entity.getAddTime()));
            channelBase.setAllowPopups(entity.getAllowPopups());
            channelBase.setShouldDisplay(entity.getShouldDisplay());
            channelBase.setIsQiyiProduced(entity.getIsQiyiProduced());
            channelBase.setExclusiveStatusIqiyi(entity.getExclusiveStatusIqiyi());
            channelBase.setInterruptHintType(entity.getInterruptHintType());
            channelBase.setSliceDelay(entity.getSliceDelay());
            channelBase.setUserCount(entity.getUserCount());
            channelBase.setCyclical(entity.getCyclical());
            channelBase.setFormal(entity.getFormal());
            channelBase.setSubjectUrl(entity.getSubjectUrl());
            // channelBase.setAutomation( entity.getAutomation());
            channelBase.setAlternatePlayCollection(entity.getAlternatePlayCollection());
            if (ChannelWebServiceConstants.SPECIAL_TABLE_NO != entity.getCarouselTableNo()) {
                channelBase.setCarouselTableNo(entity.getCarouselTableNo());
            }
            long start1 = System.currentTimeMillis();
            service.saveBase(channelBase);
            long start2 = System.currentTimeMillis();

            // 更新频道下节目最大回看时间
            updateProgramMaxPlaybackPeriod(channelBase.getId(), oldMaxPlaybackPeriod, entity.getMaxPlaybackPeriod());

            //投递图片
            JSONArray jsonArray = JSON.parseArray(entity.getLogoUrl());
            productImg(entity.getId(), jsonArray);

            List<ChannelTag> channelTags = service.getChannelTag(entity.getId());
            for (int i = 0; i < channelTags.size(); i++) {
                service.deleteTag(channelTags.get(i));
            }

            if ( StringUtils.isNotBlank( entity.getTag()) ) {
                String[] tagArr = entity.getTag().split(",");
                for (int i = 0; i < tagArr.length; i++) {
                    ChannelTag channelTag = new ChannelTag();
                    channelTag.setFatherId(entity.getId());
                    channelTag.setTag2(Long.parseLong(tagArr[i].split("_")[1]));
                    channelTag.setTag1(Long.parseLong(tagArr[i].split("_")[0]));
                    service.saveTag(channelTag);
                }
            }

            ret = true;
        }
        return ret;
    }


    @Override
    public TChannel getById(long id) throws TException {
        long start = System.currentTimeMillis();
        logger.info("[ChannelWebServiceImpl][getById][start]");
        TChannel tChannel = null;
        if (id > 0) {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            long endgetBeantime = System.currentTimeMillis();
            logger.info("[ChannelWebServiceImpl][getById][getBean(ChannelService.class)][time={}]", endgetBeantime - start);
            ChannelBase channelBase = service.getChannelBase(id);
            long getChannelBase = System.currentTimeMillis();
            logger.info("[ChannelWebServiceImpl][getById][getChannelBase][time={}]", getChannelBase - start);
            if (channelBase != null) {
                tChannel = new TChannel();
                ChannelBoss channelBoss = service.getChannelBoss(id);
                List<ChannelTag> channelTags = service.getChannelTag(id);

                tChannel.setId(id);
                tChannel.setQipuId(channelBase.getQipuId());
                tChannel.setOldQipuId(channelBase.getOldQipuId());
                tChannel.setName(channelBase.getName());
                tChannel.setShortName(channelBase.getShortName());
                tChannel.setUniversalCode(channelBase.getUniversalCode());
                tChannel.setDescription(channelBase.getDescription());
                tChannel.setPassportId(channelBase.getPassportId());
                tChannel.setPpsBaikeId(channelBase.getPpsBaikeId());
                tChannel.setLiveType(channelBase.getLiveType());
                tChannel.setType(channelBase.getType());
                tChannel.setLocation(channelBase.getLocation());
                tChannel.setOperator(channelBase.getOperator());
                tChannel.setMaxPlaybackPeriod(channelBase.getMaxPlaybackPeriod());
                tChannel.setTempName(channelBase.getTempName());
                tChannel.setTempStartTime(DateHelper.getDateStringByPattern(channelBase.getTempStartTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setTempEndTime(DateHelper.getDateStringByPattern(channelBase.getTempEndTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setQitanId(channelBase.getQitanId());
                tChannel.setOrderBy(channelBase.getOrderBy());
                tChannel.setShouldDisplay(channelBase.getShouldDisplay());
                tChannel.setAllowPopups(channelBase.getAllowPopups());
                tChannel.setQipuId(channelBase.getQipuId());
                tChannel.setLogoUrl(getProductImg(id));
                tChannel.setLogoEntityId(channelBase.getLogoEntityId());
                tChannel.setIsEnable(channelBase.getIsEnable());
                tChannel.setAddTime(DateHelper.getDateStringByPattern(channelBase.getAddTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setUpdateTime(DateHelper.getDateStringByPattern(channelBase.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setStatus(channelBoss.getStatus());
                tChannel.setIsMemeberFree(channelBoss.getIsMemeberFree());
                tChannel.setIsMemberOnly(channelBoss.getIsMemberOnly());
                tChannel.setPaidStartTime(DateHelper.getDateStringByPattern(channelBoss.getPaidStartTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setPaidEndTime(DateHelper.getDateStringByPattern(channelBoss.getPaidEndTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setIsQiyiProduced(channelBase.getIsQiyiProduced());
                tChannel.setExclusiveStatusIqiyi(channelBase.getExclusiveStatusIqiyi());
                tChannel.setInterruptHintType(channelBase.getInterruptHintType());
                tChannel.setAlternatePlayCollection(channelBase.getAlternatePlayCollection());
                tChannel.setCarouselTableNo(channelBase.getCarouselTableNo());
                tChannel.setPageUrl(channelBase.getPageUrl());
                tChannel.setSliceDelay(channelBase.getSliceDelay());
                tChannel.setSubjectUrl(channelBase.getSubjectUrl());
                tChannel.setAutomation(channelBase.getAutomation());
                tChannel.setUserCount(channelBase.getUserCount());
                tChannel.setCyclical(channelBase.getCyclical());
                tChannel.setFormal(channelBase.getFormal());
                tChannel.setThreeD(channelBase.getThreeD());
                if (channelBase.getPanoFormat() != null) {
                    tChannel.setPanoFormat(channelBase.getPanoFormat());
                }
                tChannel.setMenuShow("{\"control\":" + channelBase.getHasBroadcast() + ",\"program\":" + channelBase.getHasPrograms() + ",\"stream\":" + channelBase.getHasStream() + "}");
                String tagStr = "";

                for (int i = 0; i < channelTags.size(); i++) {
                    String _prefix = (i == channelTags.size() - 1) ? "" : ",";
                    tagStr += channelTags.get(i).getTag1() + "_" + channelTags.get(i).getTag2() + _prefix;

                }

                tChannel.setTag(tagStr);
                long endsetTime = System.currentTimeMillis();
                logger.info("[ChannelWebServiceImpl][getById][time={}]", endsetTime - start);
            }
        }
        return tChannel;
    }

    @Override
    public TChannel getByQipuId(long qipuId) throws TException {
        TChannel tChannel = null;
        if (qipuId > 0) {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            ChannelBase channelBase = service.getChannelByQipuId(qipuId);
            if (channelBase != null) {
                tChannel = new TChannel();
                ChannelBoss channelBoss = service.getChannelBoss(channelBase.getId());
                List<ChannelTag> channelTags = service.getChannelTag(channelBase.getId());
                tChannel.setOperator(channelBase.getOperator());
                tChannel.setId(channelBase.getId());
                tChannel.setQipuId(channelBase.getQipuId());
                tChannel.setOldQipuId(channelBase.getOldQipuId());
                tChannel.setName(channelBase.getName());
                tChannel.setShortName(channelBase.getShortName());
                tChannel.setUniversalCode(channelBase.getUniversalCode());
                tChannel.setDescription(channelBase.getDescription());
                tChannel.setPassportId(channelBase.getPassportId());
                tChannel.setPpsBaikeId(channelBase.getPpsBaikeId());
                tChannel.setLiveType(channelBase.getLiveType());
                tChannel.setType(channelBase.getType());
                tChannel.setLocation(channelBase.getLocation());

                tChannel.setMaxPlaybackPeriod(channelBase.getMaxPlaybackPeriod());
                tChannel.setTempName(channelBase.getTempName());
                tChannel.setTempStartTime(DateHelper.getDateStringByPattern(channelBase.getTempStartTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setTempEndTime(DateHelper.getDateStringByPattern(channelBase.getTempEndTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setQitanId(channelBase.getQitanId());
                tChannel.setLogoUrl(getProductImg(channelBase.getId()));
                tChannel.setLogoEntityId(channelBase.getLogoEntityId());
                tChannel.setOrderBy(channelBase.getOrderBy());
                tChannel.setIsEnable(channelBase.getIsEnable());
                tChannel.setShouldDisplay(channelBase.getShouldDisplay());
                tChannel.setAllowPopups(channelBase.getAllowPopups());
                tChannel.setAddTime(DateHelper.getDateStringByPattern(channelBase.getAddTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setUpdateTime(DateHelper.getDateStringByPattern(channelBase.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setStatus(channelBoss.getStatus());
                tChannel.setIsMemeberFree(channelBoss.getIsMemeberFree());
                tChannel.setIsMemberOnly(channelBoss.getIsMemberOnly());
                tChannel.setPaidStartTime(DateHelper.getDateStringByPattern(channelBoss.getPaidStartTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setPaidEndTime(DateHelper.getDateStringByPattern(channelBoss.getPaidEndTime(), "yyyy-MM-dd HH:mm:ss"));
                tChannel.setIsQiyiProduced(channelBase.getIsQiyiProduced());
                tChannel.setExclusiveStatusIqiyi(channelBase.getExclusiveStatusIqiyi());
                tChannel.setInterruptHintType(channelBase.getInterruptHintType());
                if (channelBase.getPanoFormat() != null) {
                    tChannel.setPanoFormat(channelBase.getPanoFormat());
                }
                String tagStr = "";

                for (int i = 0; i < channelTags.size(); i++) {
                    String _prefix = (i == channelTags.size() - 1) ? "" : ",";
                    tagStr += channelTags.get(i).getTag1() + "_" + channelTags.get(i).getTag2() + _prefix;

                }

                tChannel.setTag(tagStr);
            }
        }
        return tChannel;
    }

    @Override
    public TChannelPage search(TPage page, TFilter filter) throws TException {
        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);

        return service.getChanneList(page, filter);

    }

    @Override
    public boolean saveLogo(long fatherId, String url) throws TException {
        boolean ret = false;
        if (fatherId > 0) {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            int executeNum = service.updateDefaultLogoUrl( fatherId, url);
            if (executeNum > 0) {
                ret = true;
            }
        }
        return ret;
        /*
        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
        ChannelBase channelBase = service.getChannelBase(fatherId);

        List<ChannelLogo> channelLogos = service.getChannelLogo(fatherId);
        for (int i = 0; i < channelLogos.size(); i++) {
            service.deleteLogo(channelLogos.get(i));
        }
        String extend = url.substring(url.lastIndexOf(".") + 1);

        ChannelLogo channelLogo = new ChannelLogo();
        channelLogo.setFormat(extend);
        channelLogo.setFatherId(fatherId);
        channelLogo.setUrl(url);
        channelLogo.setWidth(480);
        channelLogo.setHeight(360);
        channelLogo.setUuid(UUID.randomUUID().toString());
        service.saveLogo(channelLogo);

        return true;
        */
    }
    private void writeChannelLog(long channelId, int type, String user, String descr) {
        WriteSystemLogUtil.getInstance().writeChannelLog(channelId, type, user, descr);
    }

    @Override
    public boolean checkUnique(long fatherId, String name, String universalCode) throws TException {
        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);

        boolean ret = service.checkName(fatherId, name);
        return ret == true ? service.checkUniversalCode(fatherId, universalCode) : ret;
    }

    @Override
    public boolean delChannel(long id) throws TException {
        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
        boolean delFlag = service.delChannel(id);
        if (delFlag) {
            ChannelBase channelBase = service.getChannelBase(id);
            boolean lsType = channelBase.getLiveType() != null && channelBase.getLiveType() == ChannelBase.LIVE_TYPE_LS;
            ProgramService serviceP = (ProgramService) ApplicationContextUtil.getBean(ProgramService.class);
            if (lsType) {
                Map<String, String> params = new HashMap();
                params.put("EQI_deleteFlag", "0");
                params.put("EQI_fatherId", id + "");
                TFilter tFilter = new TFilter();
                tFilter.setFilters(params);
                List<ProgramData> programDataList = serviceP.findProgramDataList(tFilter, "startPlayTime", "asc");
                for (ProgramData temp : programDataList) {
                    temp.setDeleteFlag(1);
                    WriteSystemLogUtil.getInstance().getProgramAsyncService().addVVNotify(temp);
                    WriteSystemLogUtil.getInstance().getProgramAsyncService().addTicketSysCancelNotify(temp);
                }
            }
            serviceP.deleteFlagProgramDataListByFatherId(id);
        }
        return delFlag;
    }

    @Override
    public List<Map<String, String>> getConfig(String type) throws TException {
        List<Map<String, String>> data = new ArrayList();
        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);

        List<ChannelConfig> channelConfigs = service.getConfig(type);
        for (ChannelConfig item : channelConfigs) {
            Map<String, String> temp = new HashMap();
            temp.put("id", item.getId() + "");
            temp.put("type", item.getType());
            temp.put("key", item.getKey().toString());
            temp.put("val", item.getVal());
            temp.put("descr", item.getDescr());
            data.add(temp);
        }
        return data;
    }

    @Override
    public boolean saveLog(TChannelLog entity) throws TException {
        boolean ret = false;
        if (entity != null) {
            ChannelLog channelLog = new ChannelLog();
            channelLog.setFatherId(entity.getFatherId());
            channelLog.setType(entity.getType());
            channelLog.setDescr(entity.getDescr());
            channelLog.setUser(entity.getUser());
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);

            service.saveLog(channelLog);
            ret = true;
        }

        return ret;
    }

    @Override
    public TChannelLogPage getChannelLogList(TPage page, TFilter filter) throws TException {
        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
        TChannelLogPage tChannelLogPage = service.getChannelLogList(page, filter);
        return tChannelLogPage;
    }

    @Override
    public boolean saveApiLog(String data) throws TException {
        InterfaceLogService service = (InterfaceLogService) ApplicationContextUtil.getBean(InterfaceLogService.class);
        InterfaceLog interfaceLog = JSONObject.parseObject(data, InterfaceLog.class);
        interfaceLog.setPlatform(Byte.valueOf("1"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long usageTime = (interfaceLog.getResTime().getTime() - interfaceLog.getReqTime().getTime()) / 1000;
        interfaceLog.setUsageTime(usageTime.intValue());
        if (interfaceLog.getAppkey() == null) {
            interfaceLog.setAppkey("");
        }
        service.save(interfaceLog);
        return true;
    }

    @Override
    public String getChannelCodeList(String key) throws TException {
        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
        List<ChannelCode> channelCodeList = service.getChannelCodeList(key);
        return JSON.toJSONString(channelCodeList);
    }


    @Override
    public boolean carouselTableNo(int carouselTableNo, int type, String channelId) throws TException {
        boolean ret = false;

        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);

        ChannelBase list = service.carouselTableNo(carouselTableNo, type, channelId);
        if (list != null) {
            ret = true;
        }

        return ret;
    }

    @Override
    public boolean savePanoFormat(long channelId, String panoFormat) throws TException {
        boolean ret = false;
        try {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            ChannelBase channelBase = service.getChannelBase(channelId);
            channelBase.setPanoFormat(panoFormat);
            channelBase.setIsSync(1);
            service.saveBase(channelBase);

            ret = updateProgramPanoformat(channelId, panoFormat);
        } catch (Exception e) {
            logger.error("[savePanoFormat][flag:{}][id:{}],[panoFormat={}]", ret + "", channelId + "", panoFormat);
        }

        return ret;
    }

    public String menuShow(long fatherId) throws TException {
        logger.info("Start menuShow ");
        Map<String, Integer> ret = new HashMap<>();
        long startTime = System.currentTimeMillis();
        LiveChannelStreamService liveChannelStreamService = (LiveChannelStreamService) ApplicationContextUtil.getBean(LiveChannelStreamService.class);
        int streamSize = (int) liveChannelStreamService.count(fatherId);
        logger.info("ChannelStreamWebServiceImpl getList endTime:  " + (System.currentTimeMillis() - startTime));
        ret.put("stream", streamSize);
        startTime = System.currentTimeMillis();
        ProgramWebServiceImpl programWebService = (ProgramWebServiceImpl) ApplicationContextUtil.getBean(ProgramWebServiceImpl.class);
        boolean hasPrograms = programWebService.hasPrograms(fatherId);
        logger.info("ProgramWebServiceImpl hasPrograms endTime:  " + (System.currentTimeMillis() - startTime));
        ret.put("program", hasPrograms ? 1 : 0);
        startTime = System.currentTimeMillis();
        BroadcastControlService broadcastControlService = (BroadcastControlService) ApplicationContextUtil.getBean(BroadcastControlService.class);
        boolean isSet = broadcastControlService.isSetBroadcastControl(fatherId);
        logger.info("BroadcastControlService isSetBroadcastControl endTime:  " + (System.currentTimeMillis() - startTime));
        ret.put("control", isSet ? 1 : 0);
        return JSON.toJSONString(ret);
    }


    public Long getQiTanId(String name) {
        Long ret = 0L;
//        String newName = "";
//        try {
//            newName = URLEncoder.encode(name + "直播", "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            return ret;
//        }
        String url = "http://api.t.iqiyi.com/qx_api/resource/add_resource";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36");
        Map<String, String> params = new HashMap<String, String>();
        params.put("token", "~qiTAN$resource");
        params.put("resource_type", "1");
        params.put("name", name + "直播");
        String resultValue = ApiHttpRequestUtil.doGet(url, headers, params);
        if (resultValue != null) {
            try {
                JSONObject result = JSONObject.parseObject(resultValue);
                if (Constants.CODE_SUC.equals(result.getString("code"))) {
                    ret = result.getJSONObject("data").getLongValue("resourceId");
                }
            } catch (Exception e) {
                logger.error("[ChannelWebServiceImpl][getQiTanId]", e);
            }
        }
        return ret;
    }

    public void productImg(Long fatherId, JSONArray imageDatas) {
        ProductImgUtil.productImgChannel(fatherId, imageDatas);
    }

    public String getProductImg(Long fatherId) {
        return ProductImgUtil.getChannelImg(fatherId);
    }


    public boolean channelCharge(Long qipuId, String name, String startTime, String endTime) {
        String url = Configuration.getString("channel.charge.url");
        boolean ret = false;
        Map<String, String> params = new HashMap<String, String>();
        params.put("qpid", qipuId.toString());
        params.put("makePrice", "0");
        params.put("charge", "2");
        params.put("name", name);
        params.put("liveStartTime", startTime);
        params.put("liveEndTime", endTime);

        for (int i = 0; i < 3; i++) {
            HttpClientConnection hcc = new HttpClientConnection(url, HttpClientConnection.GET_METHOD);
            hcc.setReqParams(params);
            hcc.connect();
            if (hcc.getStatus() == 200) {
                JSONObject result = JSONObject.parseObject(hcc.getBody());
                if (result.getString("code").equals("A00000")) {
                    ret = true;
                }
            }
        }
        return ret;
    }

    private void apcAdd(long channelId, String apcData) {
        logger.info("[ChannelWebServiceImpl][alternatePlayCollection][channelId={}][apcData={}]", channelId, apcData);
        Map<String, Object> params = new HashMap<>();
        try {
            List<Long> qipuIds = AlternatePlayCollectionImpl.getQipuIds(apcData);

            int size = qipuIds.size();
            if (size <= 0) {
                return;
            }
            StringBuffer qipuidsStr = new StringBuffer("");

            for (int i = 0; i < size; ++i) {
                qipuidsStr.append(qipuIds.get(i).longValue());
                if (i != size - 1) {
                    qipuidsStr.append(",");
                }
            }

            params.put("channelids", String.valueOf(channelId));
            params.put("qiPuIds", qipuidsStr.toString());

            JSONObject response = ApiHttpRequestUtil.getMethod(APC_ADD, params);
            logger.info("[ChannelWebServiceImpl][alternatePlayCollection][response=]{}", (response == null ? "npe" : response.toJSONString()));
        } catch (Exception e) {
            logger.info("[ChannelWebServiceImpl][apcAdd][Error]");
        }
    }

    @Override
    public TSearchConfig searchSearchConfig(long channelId) throws TException {
        TSearchConfig tSearchConfig = null;
        try {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            SearchSettingConfig searchConfig = service.getSearchConfig(channelId);
            if (searchConfig == null) {
                searchConfig = SettingConfigUtil.getInstance().getDefault();
            } else {
                searchConfig.readLimit();
            }

            tSearchConfig = new TSearchConfig();
            tSearchConfig.setId(searchConfig.getId());
            tSearchConfig.setCheckBossType(searchConfig.getCheckBossType());
            tSearchConfig.setCheckPublishType(searchConfig.getCheckPublishType());
            tSearchConfig.setCheckCopyRightType(searchConfig.getCheckCopyRightType());
            tSearchConfig.setOpUser(searchConfig.getOpUser());
            tSearchConfig.setOnlineLimitArr(searchConfig.getNeedOnlines());
            tSearchConfig.setRegionLimitArr(searchConfig.getNeedRegions());
        } catch (Exception e) {
            logger.error("[searchSearchConfig][id:" + channelId, e);
        }
        return tSearchConfig;
    }

    @Override
    public boolean saveSearchConfig(TSearchConfig configData) throws TException {
        boolean ret = false;
        try {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            SearchSettingConfig searchSettingConfig = new SearchSettingConfig();
            searchSettingConfig.setCheckBossType(configData.getCheckBossType());
            searchSettingConfig.setCheckPublishType(configData.getCheckPublishType());
            searchSettingConfig.setCheckCopyRightType(configData.getCheckCopyRightType());
            searchSettingConfig.setOpUser(configData.getOpUser());
            searchSettingConfig.setId(configData.getId());
            searchSettingConfig.setNeedRegions(configData.getRegionLimitArr());
            searchSettingConfig.setNeedOnlines(configData.getOnlineLimitArr());
            searchSettingConfig.recordLimit();
            searchSettingConfig.setAddTime(new Timestamp(System.currentTimeMillis()));
            service.saveSearchConfig(searchSettingConfig);
            ret = true;
        } catch (Exception e) {
            logger.error("[saveSearchConfig][id:{}]", configData.getId() + "");
        }
        return ret;
    }

    @Override
    public List<TChannel> suggestChannelInfo(long channelQipuId, String channelName, int liveType) throws TException {
        List<TChannel> data = new ArrayList();
        ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);

        List<ChannelBase> channelBase = service.suggestChannelInfo(channelQipuId, channelName, liveType);
        for (ChannelBase item : channelBase) {
            TChannel tChannel = new TChannel();
            tChannel.setName(item.getName());
            tChannel.setQipuId(item.getQipuId());
            tChannel.setLiveType(item.getLiveType());
            tChannel.setPageUrl(item.getPageUrl());
            tChannel.setDefaultLogoUrl(item.getDefaultLogoUrl());
            data.add(tChannel);
        }
        return data;
    }

    private void updateProgramMaxPlaybackPeriod(long channelId, int oldVal, int newVal) {
        logger.info("[ChannelWebServiceImpl][updateProgramMaxPlaybackPeriod][channelId={}][oldVal={}][newVal={}]", channelId, oldVal, newVal);
        if (oldVal == newVal) {
            return;
        }

        try {
            ProgramService service = (ProgramService) ApplicationContextUtil.getBean(ProgramService.class);
            int result = service.updateMaxPlaybackPeriod(channelId, newVal);
            logger.info("[ChannelWebServiceImpl][updateProgramMaxPlaybackPeriod][result={}]", result);
        } catch (Exception e) {
            logger.info("[ChannelWebServiceImpl][updateProgramMaxPlaybackPeriod][channelId={}][exception={}]", channelId, e);
        }
    }

    private boolean updateProgramPanoformat(long channelId, String panoFormat) {
        logger.info("[ChannelWebServiceImpl][updateProgramPanoformat][channelId={}][panoFormat={}]", channelId, panoFormat);

        try {
            ProgramService service = (ProgramService) ApplicationContextUtil.getBean(ProgramService.class);
            int result = service.updatePanoformat(channelId, panoFormat);
            logger.info("[ChannelWebServiceImpl][updateProgramPanoformat][result={}]", result);
            return result >= 0;
        } catch (Exception e) {
            logger.info("[ChannelWebServiceImpl][updateProgramPanoformat][channelId={}][exception={}]", channelId, e);
        }
        return false;
    }

    @Override
    public long getProgramCount(long channelId) {
        logger.info("[ChannelWebServiceImpl][getProgramCount][channelId={}]", channelId);
        long result = 0;

        try {
            ProgramService service = (ProgramService) ApplicationContextUtil.getBean(ProgramService.class);
            result = service.getProgramCountByFatherId(channelId);
            logger.info("[ChannelWebServiceImpl][getProgramCount][result={}]", result);
        } catch (Exception e) {
            logger.info("[ChannelWebServiceImpl][getProgramCount][channelId={}][exception={}]", channelId, e);
        }

        return result;
    }

    @Override
    public TChannelPcaPage findChannel(String categoryId, String channelId, String channelName, TPage page) throws TException {
        ChannelService channelService = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
        return channelService.findChannelByCategoryId(categoryId, channelId, channelName, page);
    }

    @Override
    public boolean saveThreeD(long channelId, String jsonStr) throws TException {
        boolean ret = false;
        try {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            ChannelBase channelBase = service.getChannelBase(channelId);
            channelBase.setThreeD(jsonStr);
            channelBase.setIsSync(1);
            service.saveBase(channelBase);

            ret = updateProgramThreeD(channelId, jsonStr);
        } catch (Exception e) {
            logger.error("[savePanoFormat][flag:{}][id:{}],[Format={}]", ret + "", channelId + "", jsonStr);
        }
        return ret;
    }

    private boolean updateProgramThreeD(long channelId, String threeDFormat) {
        logger.info("[ChannelWebServiceImpl][updateProgramThreeD][channelId={}][threeDFormat={}]", channelId, threeDFormat);

        try {
            ProgramService service = (ProgramService) ApplicationContextUtil.getBean(ProgramService.class);
            int result = service.updateThreeD(channelId, threeDFormat);
            logger.info("[ChannelWebServiceImpl][updateProgramThreeD][result={}]", result);
            return result >= 0;
        } catch (Exception e) {
            logger.info("[ChannelWebServiceImpl][updateProgramThreeD][channelId={}][exception={}]", channelId, e);
        }
        return false;
    }

    @Override
    public List<TChannelConfig> getAllConfigs() throws TException {
        try {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            return service.transTConfigs(service.getAllConfigs());
        } catch (Exception e) {
            logger.error("getAllConfigs", e);
            return new ArrayList<TChannelConfig>();
        }
    }

    @Override
    public int saveConfig(TChannelConfig entity) throws TException {
        try {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            logger.info("[ChannelWebServiceImpl][saveConfig][params={}]", JSONObject.toJSONString(entity));
            if (service.hasConfig(entity.getType(), entity.getKey())) {
                return -2;
            }
            ChannelConfig channelConfig = new ChannelConfig();
            channelConfig.setKey(entity.getKey());
            channelConfig.setType(entity.getType());
            channelConfig.setVal(entity.getVal());
            channelConfig.setDescr(entity.getDesc());
            channelConfig.setStatus(entity.getStatus());
            int result = service.saveConfig(channelConfig);
            logger.info("[ChannelWebServiceImpl][saveConfig][result={}]", result);
            return result >= 0 ? 1 : 0;
        } catch (Exception e) {
            logger.error("[saveConfig]", e);
            return -1;
        }
    }

    @Override
    public int editConfig(TChannelConfig entity) throws TException {
        try {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            List<Criterion> criterionList = new ArrayList<Criterion>();
            criterionList.add(Restrictions.eq("id", entity.getId()));
            List<ChannelConfig> list = service.findChannelConfigList(criterionList, null);
            if (list.size() != 1) {
                return -3;
            }
            ChannelConfig configEntity = list.get(0);
            if (configEntity.getKey().intValue() != entity.getKey()) {
                if (service.hasConfig(entity.getType(), entity.getKey())) {
                    return -2;
                }
                configEntity.setKey(entity.getKey());
            }
            configEntity.setStatus(entity.getStatus());
            configEntity.setDescr(entity.getDesc());
            configEntity.setVal(entity.getVal());
            service.editConfig(configEntity);
        } catch (Exception e) {
            logger.error("editConfig", e);
            return -999;
        }
        return 1;
    }

    @Override
    public List<TChannelConfig> filterConfigs(String type, String status, String descr) throws TException {
        try {
            ChannelService service = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            List<Criterion> criterionList = new ArrayList<Criterion>();
            List<Order> orderList = new ArrayList<>();
            if (StringUtils.isNotBlank(type)) {
                criterionList.add(Restrictions.ilike("type", type));
                orderList.add(Order.asc("type"));
            }
            if (StringUtils.isNotBlank(status) &&StringUtils.isNumeric( status) ) {
                criterionList.add(Restrictions.eq("status",Integer.valueOf(status) ));
            }

            if (StringUtils.isNotBlank(descr)) {
                criterionList.add(Restrictions.like("descr", descr));
            }

            orderList.add(Order.asc("key"));
            List<ChannelConfig> list = service.findChannelConfigList(criterionList, orderList);
            return service.transTConfigs(list);
        } catch (Exception e) {
            logger.error("filterConfigs", e);
            return null;
        }

    }

}
